from helpers import updateInfo
import datetime
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db


class MainPage(webapp.RequestHandler):
    """ Build a RSS feed page class """
    def get(self):
        
        self.response.headers['Content-Type'] = 'text/xml'
         
        self.response.out.write('<rss version="2.0">\n')
        self.response.out.write('<channel>\n')
        self.response.out.write('<title>Trend Stock Exchange</title>\n')
        self.response.out.write('<link>http://mytrendse3.appspot.com</link>\n')
        self.response.out.write('<description>TrendSE website</description>\n')
        self.response.out.write('<language>en</language>\n')
        self.response.out.write('<managingEditor>treands.team@gmail.com</managingEditor>\n')
        self.response.out.write('<webMaster>treands.team@gmail.com</webMaster>\n')
        self.response.out.write('<lastBuildDate>%s</lastBuildDate>\n' % datetime.date.today())
        
        self.response.out.write('\n')
        
        q_1 = db.GqlQuery("SELECT * FROM StocksData ORDER BY precentChange DESC LIMIT 0,5")
        i=1
        
        for stock in q_1:
            self.response.out.write('<item>\n')
            self.response.out.write('<title>Stock Name: %s</title>\n'%(stock.stockname))
            printPercentage, _, _=updateInfo.getPerInfo(stock.precentChange)
            if stock.precentChange<1:
                dayChangeSign="- "
            elif stock.precentChange>1:
                dayChangeSign="+ "
            else:
                dayChangeSign=""
    
            
            self.response.out.write('<description>Daily precent change (%s%0.2f)</description>\n' % (dayChangeSign,printPercentage))
            self.response.out.write('<link>http://mytrendse3.appspot.com/trendProfile?TKey=%s</link>\n'% stock.key())
            if stock.updatedate:
                self.response.out.write('<pubDate>Last update date %s</pubDate>\n' % stock.updatedate)
            self.response.out.write('</item>\n')
            i=i+1
    
            
        
        self.response.out.write('</channel></rss>')
     

application = webapp.WSGIApplication(
                                     [('/feed.xml', MainPage)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()